package com.Cychat.post.lstener;

import com.Cychat.post.entity.dto.PostDTO;
import com.Cychat.post.entity.mq.CollectMonitor;
import com.Cychat.commons.entity.pojo.MessageReminding;
import com.Cychat.post.service.MessageRemindingService;
import com.Cychat.post.service.PostService;
import com.Cychat.post.service.WebSocketNotificationService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class CollectListener {
    @Autowired
    private MessageRemindingService messageRemindingService;
    @Autowired
    private PostService postService;
    @Autowired
    private WebSocketNotificationService webSocketNotificationService;

    @RabbitListener(queues = "cychat.collect")
    public void workListener(CollectMonitor monitor) {
        System.out.println("========== 收藏监听器被触发 ==========");
        System.out.println("收藏者ID: " + monitor.getUserId());
        System.out.println("帖子ID: " + monitor.getPostId());

        PostDTO postById = postService.getPostById(monitor.getPostId(), monitor.getUserId());
        String content = "收藏了你的帖子：" + postById.getTitle();
        MessageReminding messageReminding = new MessageReminding(null, monitor.getUserId(), postById.getUserId(),
                monitor.getPostId(), content, 0, new Date(), new Date());
        messageRemindingService.save(messageReminding);

        System.out.println("提醒内容: " + content);

        // 通过WebSocket推送通知给发帖人
        try {
            webSocketNotificationService.sendNotificationMessage(
                    postById.getUserId(), // 接收者ID（发帖人）
                    monitor.getUserId(), // 发送者ID（收藏者）
                    content, // 消息内容
                    "互动消息", // 发送者名称
                    "https://pet-java-chengdu-123.oss-cn-chengdu.aliyuncs.com/%E7%94%9F%E6%88%90%E5%AE%98%E6%96%B9%E7%8C%AB%E7%8B%97%20logo.png", // 发送者头像
                    monitor.getPostId() // 帖子ID
            );
            System.out.println("WebSocket推送结果: 成功");
        } catch (Exception e) {
            System.err.println("WebSocket推送结果: 失败 - 错误: " + e.getMessage());
            e.printStackTrace();
        }

        System.out.println("========== 收藏监听器处理完成 ==========");
    }
}